import React from 'react';
import {connect} from 'dva/index';
import { Button, Col, Form, Input, message, Modal, Popconfirm, Radio, Row, Select, Table, Tabs } from 'antd';
import RightBox from '../../common/rightBox';
import CurrencySelect from '../../common/CurrencySelect';
import RightConstants from '../../../utils/RightConstants';
import AddFee from '../chargeTemplate/AddFee';

const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const R = require("ramda");
const TabPane = Tabs.TabPane;


const chargeTemplateDetail = Form.create()(class ChargeTemplateDetail extends React.Component {
    constructor(props) {
        super(props);
        this.initData(props.dataSource, true);
        this.state = {
            open: false,
            disabled: false,
            id:null
        }
    }

    componentWillReceiveProps(nextProps) {
        if (!R.equals(this.props.dataSource)(nextProps.dataSource)) {
            this.initData(nextProps.dataSource)
        }
    }


    initData = (dataSource, flag) => {
        let charges = dataSource.charges ? dataSource.charges : []
        dataSource = R.isNil(dataSource) ? {} : dataSource;
        if (flag) {
            this.state = {
                open: false,
                disabled: false,
                marketDisabled: false,
                isAllocation: false,        //判断是否分配操作员
                newAdd:false,  //判断是否分为新增模板

                charges
            }
        } else {
            this.setState({
                charges
            })
        }
    }
    //null, false,true  新增
    //record.id, false,false  编辑
    handleOpen = (id,disabled,newAdd) => {
        let charges = this.props.dataSource && this.props.dataSource.charges && id ? this.props.dataSource.charges : [];
        this.setState({ open: true,id, charges,disabled,newAdd });

    }

    handleDelete = (record) => {
        let charges = R.difference(this.state.charges, [record]);
        this.setState({ charges });
    }

    handleAddOrUpdateFee = (record) => {
        let charges = [];
        //修改逻辑
        R.map((feeTerm) => {
            if (feeTerm.id === record.id) {
                charges.push(record);
            } else {
                charges.push(feeTerm);
            }
        }, this.state.charges);
        //新增逻辑
        if (!R.contains(record, charges)) {
            charges.push(record);
        }
        this.setState({ charges });

    }

    handleCancel = () => {
        this.setState({ open: false });
        this.props.form.resetFields();
    }

    //record  //这个需要调编辑
    handleOpenProductDetail=(record,newAdd,edit)=>{
        this.props.dispatch({ type: 'feeItem/getAllFeeItems' ,payload: { id:record.id } });
        this.addFee.handleOpen(record,newAdd,edit);
    }

    // this.state.id, true  新增模板中的新增费用
    handleAddFee = (id,) => {  //新增、修改费用
        let newAdd = this.state.newAdd;
        this.props.dispatch({ type: 'feeItem/getAllFeeItems' ,payload: { id } });
        this.addFee.handleOpen(id ,newAdd);
    }

        handleConfirm = () => {
        let newAdd = this.state.newAdd;
        this.props.form.validateFields({ force: true }, (errors, values) => {
            if (errors) return;
            values.id = this.props.dataSource && this.props.dataSource.id ? this.props.dataSource.id : null;
            values.begindate = R.isNil(values.begindate) || R.isEmpty(values.begindate) ? "" : values.begindate.format(dateFormat);
            values.enddate = R.isNil(values.enddate) || R.isEmpty(values.enddate) ? "" : values.enddate.format(dateFormat);
            values.charges = this.state.charges;
            let dispatchType = values.id ? 'chargeTemplate/update' : 'chargeTemplate/add';
            if (!R.equals(R.pick(Object.keys(values), this.props.dataSource), values)) {
                    this.props.dispatch({
                        type: dispatchType,
                        payload: {
                            dataSource: values,
                            ...values,
                            newAdd:newAdd,
                            onSuccess: () => {
                                this.handleCancel();
                                if (this.props.refreshList) this.props.refreshList();
                            }
                        }
                    })
                } else this.handleCancel();

        });
    }


    columns = [
        {title: '费用名称', key:'feeItemName', dataIndex: 'feeItemName'},
        {title: '币种', key: 'currency', dataIndex: 'currency'},
        {title: '单价', dataIndex: 'fee', key: 'fee'},
        {title: '数量', dataIndex: 'count', key: 'count'},
        {title: '合计', dataIndex: 'quotePrice', key: 'quotePrice'},
        {title: '汇率', dataIndex: 'rate', key: 'rate'},
        {title: '人民币合计', dataIndex: 'quotePriceCny', key: 'quotePriceCny'},
        {title: '结算单位', dataIndex: 'settlementUnit', key: 'settlementUnit'},
        {title: '操作', key: 'key_oprator',
            render: record => {
                let editLink = <RightBox resource={RightConstants.QUOTATIONSUPPORT.QUOTATIONSUPPORT_FEEITEM_EDIT} split={true}><a href="#" onClick={this.handleOpenProductDetail.bind(this, record,false,true)}>编辑</a></RightBox>
                let deleteLink = <Popconfirm onConfirm={this.handleDelete.bind(this, record)} okText="是" cancelText="否"
                                             placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除?'}>
                    <a href="#">删除</a>
                </Popconfirm>
                deleteLink = <RightBox resource={RightConstants.QUOTATIONSUPPORT.QUOTATIONSUPPORT_FEEITEM_DELETE} >{deleteLink}</RightBox>
                return (
                    <span>{editLink}{deleteLink}</span>
                );
            }
        }
    ];
    render() {
        let dataSource = this.props.chargeTemplate.dataSource ? this.props.chargeTemplate.dataSource : {};
        let formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } };

        const { getFieldDecorator } = this.props.form;
        let footer = [
            <Button key="save" size="large" loading={this.props.loading} onClick={this.handleConfirm.bind(this)} style={{ display: this.state.disabled ? 'none' : 'inline-block' }}>保存</Button>,
            <Button key="cancel" size="large" loading={this.props.loading} onClick={this.handleCancel.bind(this, true)}>{this.state.disabled ? "关闭" : "取消"}</Button>
        ];
        return (
            <Modal maskClosable={false} visible={this.state.open} title={"费用项目详情"} width={1000} confirmLoading={this.props.loading} onCancel={this.handleCancel.bind(this)} footer={footer}>
                <Form>
                    <Row>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="模板名称" hasFeedback>
                                {getFieldDecorator('name', {
                                    rules: [{
                                        required: true, message: '请输入模板名称',
                                    }],
                                    // initialValue:  (this.state.newAdd) ? null : dataSource.name
                                    initialValue:  dataSource.name
                                })(
                                    <Input disabled={this.state.disabled} maxLength="200" />
                                )}
                            </FormItem>

                        </Col>
                        <Col span={12}>
                            <FormItem {...formItemLayout} label="模板类型" hasFeedback>
                                {getFieldDecorator('type', {
                                    rules: [{
                                        required: true, message: '请输入中文名称',
                                    }],
                                    // initialValue: this.state.newAdd ? () : dataSource.type
                                        initialValue:  dataSource.type
                                })(
                                    <Select disabled={this.state.disabled}>
                                        <Select.Option value="0">应付</Select.Option>
                                        <Select.Option value="1">应收</Select.Option>
                                    </Select>
                                )}
                            </FormItem>

                        </Col>
                    </Row>
                    <div>
                        <Row>
                            <Col span={3}
                                 style={{ float: 'right',}}
                            >

                                <RightBox resource={RightConstants.QUOTATIONSUPPORT.QUOTATIONSUPPORT_FEEITEMTEMPLATE_ADD}>
                                    <Button type="primary" icon="plus" size={'default'}disabled={this.state.disabled} onClick={this.handleAddFee.bind(this, this.state.id, true)}>新增费用</Button></RightBox>
                            </Col>
                        </Row>
                        <Tabs tabPosition={'top'}>
                            <TabPane tab="费用条目">
                                <Table
                                    // rowKey={record => record.id}
                                    rowKey='id'
                                    loading={this.props.loading}
                                    dataSource={this.state.charges}
                                    columns={this.columns}
                                    bordered={true}
                                    pagination={false}
                                />
                            </TabPane>
                        </Tabs>
                    </div>


                </Form >

                <AddFee wrappedComponentRef={(inst) => this.addFee = inst} orderId={this.props.orderId}refreshList={this.handleSearch} handleAddOrUpdateFee={this.handleAddOrUpdateFee}/>

            </Modal >
        )
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.chargeTemplate, chargeTemplate: state.chargeTemplate, supplier: state.supplier,feeItem: state.feeItem,
    };
}

export default connect(mapStateToProps)(chargeTemplateDetail);